<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\controller\v1;

use app\api\model\DrivingLicense as DrivingLicenseModel;
use app\api\model\InterfaceLog;
use app\api\model\Order as OrderModel;
use app\api\model\Subscribe as SubscribeModel;
use app\api\model\UserWeixin as UserWeixinModel;
use app\api\service\Car as CarInterface;
use app\api\service\Token;
use app\lib\enum\CarActionEnum;
use app\lib\enum\CarEnum;
use app\lib\enum\OrderStatusEnum;
use app\lib\enum\ZtEnum;
use app\lib\exception\ParameterException;
use app\lib\exception\SuccessMessage;
use think\Config;
use think\Db;
use think\Request;
use WeMini\Newtmpl;
use Yurun\Util\HttpRequest;

class Car extends BaseController
{
    private $is_open_sub = 1; // 是否是真实预约
    private $order; // 订单数据
    private $config; // 微信配置
    private $miniprogram_state = 'formal'; // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版

    /**
     * @Desc 查询预约手机号状态
     *
     * @param $mobile
     *
     * @return array
     */
    public function checkMobileStatus($mobile)
    {
        if ($this->is_open_sub) {
            $data = json_encode(['lxdh' => $mobile], JSON_UNESCAPED_UNICODE);
            $param = [
                'action' => CarActionEnum::CHECK_MOBILE,
                'data'   => $data,
            ];
            $car = new CarInterface($param);
            $result = $car->appointment();
            $logData = [
                'code'  => CarActionEnum::CHECK_MOBILE,
                'title' => '查询手机号状态',
                'limit' => CarActionEnum::CHECK_MOBILE_NUM,
            ];
            $this->addInterfaceLog($logData);
        } else {
            $result = [
                'code' => 1,
                'msg'  => '成功',
            ];
        }
        return $result;
    }

    /**
     * @Desc 写入预约信息
     */
    public function writeInSubscribeInformation()
    {
        if ($this->is_open_sub) {
            $info = Request::instance()->post();
            // 获取行驶证信息
            $driving = DrivingLicenseModel::getDetail($info['driving_license_id']);
            // 生成流水号
            $lsh = Config::get('subscribe.babh') . date('ymd') . randomStr(5);
            // 格式化预约时间
            $subscribe_date = strtotime($info['subscribe_date']);
            $data = [
                'lsh'     => $lsh, // 流水号
                'jczbh'   => $info['jczbh'], // 检测站编号
                'jczmc'   => $info['jczmc'], // 检测站名称
                'yyrq'    => (int)date('Ymd', $subscribe_date), // 预约日期 20200202
                'yysj'    => (int)date('H', $subscribe_date), // 预约整点时间(8.9.10)
                'hphm'    => $driving['license_number'], // 号牌号码
                'hpys'    => $driving['license_color'], // 号牌颜色
                // 'clsbdh6' => substr($driving['vehicle_identification'], -6), // 车架号后6位
                'clsbdh6' => $driving['vin'] ?: substr($driving['vehicle_identification'], -6), // 车架号后6位
                'lxdh'    => $info['lxdh'], // 预约手机号
                'syr'     => $driving['user_name'], // 所有人
                'cllx'    => $driving['license_typename'], // 车辆类型
            ];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $param = [
                'action' => CarActionEnum::SUBSCRIBE,
                'data'   => $data,
            ];
            $car = new CarInterface($param);
            $result = $car->appointment();
            $result['lsh'] = $lsh;
            $logData = [
                'code'  => CarActionEnum::SUBSCRIBE,
                'title' => '写入预约车辆信息',
                'limit' => CarActionEnum::SUBSCRIBE_NUM,
            ];
            $this->addInterfaceLog($logData);
        } else {
            $lsh = Config::get('subscribe.babh') . date('ymd') . randomStr(5);
            $result = [
                'code' => 1,
                'msg'  => '成功',
                'lsh'  => $lsh,
            ];
        }
        return $result;
    }

    /**
     * @Desc 先下单再写入预约信息
     *
     * @param $info
     *
     * @return array|mixed
     */
    public function writeInSubscribeInformation2($info)
    {
        // $info = ['jczbh' => '2300000313', 'jczmc' => '松北区捷安检车站', 'subscribe_date' => '2021-03-03 16:00', 'driving_license_id' => '46117', 'lxdh' => '15331881286',];
        if ($this->is_open_sub) {
            // 获取行驶证信息
            $driving = DrivingLicenseModel::getDetail($info['driving_license_id']);
            // 格式化预约时间
            $subscribe_date = strtotime($info['subscribe_date']);
            $data = [
                'lsh'     => $info['lsh'], // 流水号
                'jczbh'   => $info['jczbh'], // 检测站编号
                'jczmc'   => $info['jczmc'], // 检测站名称
                'yyrq'    => (int)date('Ymd', $subscribe_date), // 预约日期 20200202
                'yysj'    => (int)date('H', $subscribe_date), // 预约整点时间(8.9.10)
                'hphm'    => $driving['license_number'], // 号牌号码
                'hpys'    => $driving['license_color'], // 号牌颜色
                // 'clsbdh6' => substr($driving['vehicle_identification'], -6), // 车架号后6位
                'clsbdh6' => $driving['vin'] ?: substr($driving['vehicle_identification'], -6), // 车架号后6位
                'lxdh'    => $info['lxdh'], // 预约手机号
                'syr'     => $driving['user_name'], // 所有人
                'cllx'    => $driving['license_typename'], // 车辆类型
            ];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $param = [
                'action' => CarActionEnum::SUBSCRIBE,
                'data'   => $data,
            ];
            $car = new CarInterface($param);
            $result = $car->appointment();
            // {code: 1, msg: "提示信息"}
            $logData = [
                'code'  => CarActionEnum::SUBSCRIBE,
                'title' => '写入预约车辆信息',
                'limit' => CarActionEnum::SUBSCRIBE_NUM,
            ];
            $this->addInterfaceLog($logData);
        } else {
            $result = [
                'code' => 1,
                'msg'  => '成功',
            ];
        }
        return $result;
    }

    /**
     * @Desc 查询预约信息
     *
     * @param $lsh
     *
     * @return array
     */
    public function checkSubscribeStatus($lsh)
    {
        $data = json_encode(['lsh' => $lsh], JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::CHECK_SUBSCRIBE,
            'data'   => $data,
        ];
        $car = new CarInterface($param);
        $result = $car->appointment();
        // $logData = [
        //     'code'  => CarActionEnum::CHECK_SUBSCRIBE,
        //     'title' => '查询预约信息',
        //     'limit' => CarActionEnum::CHECK_SUBSCRIBE_NUM,
        // ];
        // $this->addInterfaceLog($logData);
        return $result;
    }

    /**
     * @Desc 更新订单状态
     * @return SuccessMessage
     */
    public function updateOrderZt()
    {
        $param = Request::instance()->put();
        return OrderModel::updateOrderZt($param);
    }

    /**
     * @Desc 更新用户数据
     *
     * @param $mobile
     *
     * @return array
     */
    public function updateUserMobile($mobile)
    {
        return UserWeixinModel::updateUserMobile($mobile);
    }

    /**
     * @Desc 注册手机号
     * @return array
     */
    public function registerMobile()
    {
        $param = Request::instance()->post();
        $data = json_encode($param, JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::REGISTER,
            'data'   => $data,
        ];
        $car = new CarInterface($param);
        $result = $car->appointment();
        $logData = [
            'code'  => CarActionEnum::REGISTER,
            'title' => '注册预约手机号',
            'limit' => CarActionEnum::REGISTER_NUM,
        ];
        $this->addInterfaceLog($logData);
        return $result;
    }

    /**
     * @Desc 取消预约检车
     *
     * @param $lsh
     *
     * @return array
     */
    public function cancelCarOrder($lsh)
    {
        $data = json_encode(['lsh' => $lsh], JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::CANCEL_SUBSCRIBE,
            'data'   => $data,
        ];
        $car = new CarInterface($param);
        $result = $car->appointment();
        $logData = [
            'code'  => CarActionEnum::CANCEL_SUBSCRIBE,
            'title' => '取消预约信息',
            'limit' => CarActionEnum::CANCEL_SUBSCRIBE_NUM,
        ];
        $this->addInterfaceLog($logData);
        if (1 == $result['code']) {
            OrderModel::update(['zt' => ZtEnum::CANCELLED], ['lsh' => $lsh]);
            $subscribe_id = Db::name('order')->where('lsh', '=', $lsh)->value('subscribe_id');
            if (45 == $this->order['company_id'] && 1 == $this->order['vehicle_id']) {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_gas')->update();
            } elseif (45 == $this->order['company_id'] && (2 == $this->order['vehicle_id'] || 3 == $this->order['vehicle_id'])) {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_diesel')->update();
            } else {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num')->update();
            }
        }
        return $result;
    }

    /**
     * @Desc 获取尝试次数
     * @return array
     */
    public function getRegisterMobileTryLog()
    {
        $id = Token::getUidFromCache();
        $try_times = Db::name('user_register_error_log')->where('user_weixin_id', '=', $id)->where('try_date', '=', date('Y-m-d'))->value('try_times');
        if (!$try_times || CarEnum::TRY_TIMES > $try_times) {
            $result = [
                'code' => 1,
                'msg'  => 'ok',
            ];
        } else {
            $result = [
                'code' => 0,
                'msg'  => 'no',
            ];
        }
        return $result;
    }

    /**
     * @Desc 注册手机号失败次数
     * @return array
     */
    public function insertRegisterMobileTryLog()
    {
        $id = Token::getUidFromCache();
        $date = date('Y-m-d');
        $where = [
            'user_weixin_id' => $id,
            'try_date'       => $date,
        ];
        $try_times = Db::name('user_register_error_log')->where($where)->value('try_times');
        $num = CarEnum::TRY_TIMES;
        if ($num <= $try_times) {
            throw new ParameterException([
                'message' => "错误次数超过{$num}次，请明天再试",
            ]);
        }
        if (!$try_times) {
            $insertData = [
                'user_weixin_id' => $id,
                'try_date'       => $date,
                'try_times'      => 1,
            ];
            Db::name('user_register_error_log')->insert($insertData);
            $result = [
                'tryNum' => 1,
                'num'    => $num - 1,
            ];
        } else {
            Db::name('user_register_error_log')->where($where)->inc('try_times')->update();
            $result = [
                'tryNum' => $try_times + 1,
                'num'    => $num - ($try_times + 1),
            ];
        }
        return $result;
    }

    /**
     * @Desc 查询所有订单状态
     */
    public function checkAllSubscribeStatus()
    {
        $order = Db::name('order');
        // 1.查询今天起的所有审核订单
        // $list = $order->field('order_id, open_id, lsh, subscribe_id, create_time')->whereIn('zt', [ZtEnum::WAIT_AUDIT, ZtEnum::AUDITING])->select();
        $list = $order->field('order_id, company_id, vehicle_id, open_id, lsh, subscribe_id, create_time')->whereIn('zt', [ZtEnum::WAIT_AUDIT, ZtEnum::AUDITING])->where('subscribe_date', '>', strtotime(date('Y-m-d')))->select();
        if (0 == count($list)) {
            return;
        }
        $time = time();
        $count = 0; // 调用查询接口次数
        // 2.循环查询每个订单状态
        foreach ($list as $item) {
            // 下单30秒内的订单跳过
            if ($time - $item['create_time'] <= 30) {
                continue;
            }
            $subscribe_id = $item['subscribe_id'];
            // 查询当前循环的订单状态
            $res = $this->checkSubscribeStatus($item['lsh']);
            // 0.1秒后下一次循环
            usleep(100000);
            $count++;
            // 访问出错, 跳过
            if (0 == $res['code']) {
                continue;
            }
            $data = json_decode($res['data'], true);
            $message = [
                'order_id' => $item['order_id'],
                'open_id'  => $item['open_id'],
            ];
            // 3.预约成功 - zt=2
            switch ($data['zt']) {
                case ZtEnum::SUCCESS:
                    // 3.1 更新订单状态
                    $updateData = [
                        'zt'          => $data['zt'],
                        'update_time' => $time,
                    ];
                    $order->where('order_id', '=', $item['order_id'])->update($updateData);
                    // 3.2 传递订单给收银系统
                    $this->generatePaymentOrderData($item['order_id']);
                    // 3.3 给用户发消息
                    $message['type'] = 'subscribeComplete';
                    $this->sendSubscribeMessage($message);
                    break;
                case ZtEnum::FAILED:
                    // 3.1 更新订单状态
                    $updateData = [
                        'zt'           => $data['zt'],
                        'sbyy'         => $data['sbyy'],
                        'order_status' => OrderStatusEnum::CANCELLED,
                        'update_time'  => $time,
                        'cancel_time'  => $time,
                    ];
                    $order->where('order_id', '=', $item['order_id'])->update($updateData);
                    // 3.2 取消/未通过订单恢复预约数量
                    if (45 == $item['company_id'] && 1 == $item['vehicle_id']) {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_gas')->update();
                    } elseif (45 == $item['company_id'] && (2 == $item['vehicle_id'] || 3 == $item['vehicle_id'])) {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_diesel')->update();
                    } else {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num')->update();
                    }
                    // 3.3 给用户发消息
                    $message['type'] = 'failed';
                    $this->sendSubscribeMessage($message);
                    break;
                case ZtEnum::CANCELLED:
                    // 3.1 更新订单状态
                    $updateData = [
                        'zt'           => $data['zt'],
                        'order_status' => OrderStatusEnum::CANCELLED,
                        'update_time'  => $time,
                        'cancel_time'  => $time,
                    ];
                    $order->where('order_id', '=', $item['order_id'])->update($updateData);
                    // 3.2 取消/未通过订单恢复预约数量
                    if (45 == $item['company_id'] && 1 == $item['vehicle_id']) {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_gas')->update();
                    } elseif (45 == $item['company_id'] && (2 == $item['vehicle_id'] || 3 == $item['vehicle_id'])) {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_diesel')->update();
                    } else {
                        (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num')->update();
                    }
                    break;
                case ZtEnum::CHECKING:
                    // 3.1 更新订单状态
                    $updateData = [
                        'zt'          => $data['zt'],
                        'update_time' => $time,
                    ];
                    $order->where('order_id', '=', $item['order_id'])->update($updateData);
                    break;
                case ZtEnum::COMPLETED:
                    // 3.1 更新订单状态
                    $updateData = [
                        'zt'           => $data['zt'],
                        'order_status' => OrderStatusEnum::COMPLETED,
                        'update_time'  => $time,
                        'finish_time'  => $time,
                    ];
                    $order->where('order_id', '=', $item['order_id'])->update($updateData);
                    break;
            }
        }
        $logData = [
            'code'  => CarActionEnum::CHECK_SUBSCRIBE,
            'title' => '查询预约信息',
            'limit' => CarActionEnum::CHECK_SUBSCRIBE_NUM,
            'num'   => $count,
        ];
        $this->addInterfaceLog($logData);
        echo date('Y-m-d H:i:s') . ' -> ' . $count . "\r\n";
    }

    /**
     * @Desc 更新所有已完成订单的状态
     */
    public function updateCompletedOrderStatus()
    {
        // if (ZtEnum::COMPLETED == $data['zt']) {
        //     $updateData[] = [
        //         'order_id'     => $item['order_id'],
        //         'zt'           => $data['zt'],
        //         'order_status' => OrderStatusEnum::COMPLETED,
        //         'finish_time'  => time(),
        //     ];
        // }
        // if (count($updateData)) {
        //     $order->saveAll($updateData);
        // }
    }

    /**
     * @Desc 发送订阅消息
     *
     * @param array $message
     *
     * @return SuccessMessage
     */
    public function sendSubscribeMessage2($message = [])
    {
        $request = Request::instance();
        $param = $message;
        if (Request::instance()->isPost()) {
            $param = $request->post();
        }
        $this->order = OrderModel::getOrderDetailFromCar($param['order_id']);
        $this->config = Config::get('wechat');
        $mini = new Newtmpl($this->config);
        $data = '';
        switch ($param['type']) {
            case 'subscribeWaitAudit':
            case 'subscribeAuditing':
            case 'failed':
                $data = $this->generateAuditNoticeData($param);
                break;
            case 'subscribeSuccess':
                $data = $this->generateSuccessData($param['type']);
                break;
            case 'subscribePaid':
                $data = $this->generatePaidData($param['type']);
                break;
            case 'subscribeCanceled':
                $data = $this->generateCanceledData($param['type']);
                break;
            case 'subscribeComplete':
                $data = $this->generateCompleteData($param);
                break;
        }
        $mini->send($data);
        return new SuccessMessage();
    }

    /**
     * @Desc 发送订阅消息
     *
     * @param array $message
     *
     * @return SuccessMessage
     */
    public function sendSubscribeMessage($message = [])
    {
        $request = Request::instance();
        $param = $message; // $message = ['order_id' => $item['order_id'],'open_id'  => $item['open_id'],'type'  => 'subscribeComplete'];
        if ($request->isPost()) {
            $param = $request->post();// param = {type: type, order_id: order_id}
        }
        $this->order = OrderModel::getOrderDetailFromCar($param['order_id']);
        $this->config = Config::get('wechat');
        $mini = new Newtmpl($this->config);
        $data = '';
        switch ($param['type']) {
            case 'subscribeWaitAudit':
            case 'subscribeAuditing':
                $data = $this->generateWaitAuditData($param['type']);
                break;
            case 'failed':
                $data = $this->generateAuditNoticeData($param);
                break;
            case 'subscribeSuccess':
                $data = $this->generateSuccessData($param['type']);
                break;
            case 'subscribePaid':
                $data = $this->generatePaidData($param['type']);
                break;
            case 'subscribeCanceled':
                $data = $this->generateCanceledData($param['type']);
                break;
            case 'subscribeComplete':
                $data = $this->generateCompleteData($param);
                break;
        }
        $mini->send($data);
        // return new SuccessMessage();
        return $param;
    }

    /**
     * @Desc 生成待审核数据
     *
     * @param $type
     *
     * @return array
     */
    private function generateWaitAuditData($type)
    {
        $data = [
            'character_string2' => ['value' => $this->order['order_sn']], // 订单号
            'thing1'            => ['value' => '预约检车(待审核)'], // 预约项目
            'car_number3'       => ['value' => $this->order['license_number']], // 车牌号
            'phone_number5'     => ['value' => $this->order['mobile']], // 手机号
            'time4'             => ['value' => $this->order['subscribe_date']], // 预约时间
        ];
        return [
            'touser'            => Token::getOpenidFromCache(),
            'template_id'       => $this->config[$type],
            'page'              => '/pages/order-detail/order-detail?id=' . $this->order['order_id'],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    /**
     * @Desc 生成预约成功数据
     *
     * @param $type
     *
     * @return array
     */
    private function generateSuccessData($type)
    {
        $data = [
            'character_string1' => ['value' => $this->order['subscribe_code']], // 预约码 123456
            'thing3'            => ['value' => $this->order['company_name']], // 预约门店
            'phone_number4'     => ['value' => $this->order['telephone']], // 门店电话
            'thing5'            => ['value' => '请在预约日期进行检车，逾期账户将被锁定'], // 备注信息
            'time2'             => ['value' => $this->order['update_time']], // 预约时间
        ];
        return [
            'touser'            => Token::getOpenidFromCache(),
            'template_id'       => $this->config[$type],
            'page'              => '/pages/order-detail/order-detail?id=' . $this->order['order_id'],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    /**
     * @Desc 生成订单支付数据
     *
     * @param $type
     *
     * @return array
     */
    private function generatePaidData($type)
    {
        $data = [
            'character_string1' => ['value' => $this->order['order_sn']], // 订单编号
            'amount2'           => ['value' => $this->order['total_amount']], // 订单金额
            'car_number5'       => ['value' => $this->order['license_number']], // 车牌号
            'thing4'            => ['value' => '订单支付成功，请耐心等待检车'], // 温馨提示
            'date3'             => ['value' => $this->order['update_time']], // 下单时间
        ];
        return [
            'touser'            => Token::getOpenidFromCache(),
            'template_id'       => $this->config[$type],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    /**
     * @Desc 生成预约取消数据
     *
     * @param $type
     *
     * @return array
     */
    private function generateCanceledData($type)
    {
        $data = [
            'thing1'        => ['value' => '预约检车'], // 服务项目
            'thing3'        => ['value' => $this->order['company_name']], // 服务门店
            'phone_number4' => ['value' => $this->order['telephone']], // 门店电话
            'time2'         => ['value' => $this->order['subscribe_date']], // 服务时间
            'thing6'        => ['value' => '取消检车'], // 取消原因
        ];
        return [
            'touser'            => Token::getOpenidFromCache(),
            'template_id'       => $this->config[$type],
            'page'              => '/pages/order-detail/order-detail?id=' . $this->order['order_id'],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    /**
     * @Desc 生成预约成功数据
     *
     * @param $param
     *
     * @return array
     */
    private function generateCompleteData($param)
    {
        $user_name = mb_substr($this->order['user_name'], 0, 19);
        if (array_key_exists('open_id', $param)) {
            $open_id = $param['open_id'];
        } else {
            $open_id = Token::getOpenidFromCache();
        }
        $data = [
            'thing14'        => ['value' => $user_name], // 所有人姓名
            'phone_number12' => ['value' => $this->order['mobile']], // 预约人电话
            'car_number2'    => ['value' => $this->order['license_number']], // 车牌号码
            'thing4'         => ['value' => $this->order['company_name']], // 检车站名称
            'date5'          => ['value' => $this->order['subscribe_date']], // 预约时间
        ];
        return [
            'touser'            => $open_id,
            'template_id'       => $this->config[$param['type']],
            'page'              => '/pages/order-detail/order-detail?id=' . $this->order['order_id'],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    private function generateAuditNoticeData($param)
    {
        $phrase1 = $thing3 = '';
        if (array_key_exists('open_id', $param)) {
            $open_id = $param['open_id'];
        } else {
            $open_id = Token::getOpenidFromCache();
        }
        switch ($param['type']) {
            case 'subscribeWaitAudit':
                $phrase1 = '待审核';
                $thing3 = '请刷新状态，显示预约成功后方可检车';
                break;
            case 'subscribeAuditing':
                $phrase1 = '审核中';
                $thing3 = '请刷新状态，显示预约成功后方可检车';
                break;
            case 'failed':
                $phrase1 = '审核未通过';
                $thing3 = '请进入订单详情查看具体原因';
                break;
        }
        $sbyy = '无';
        if (!empty($this->order['sbyy'])) {
            $str = preg_replace('/车牌号【.*】预约不成功。
/', '', $this->order['sbyy']);
            $sbyy = mb_substr($str, 0, 15) . '...';
        }
        $data = [
            'character_string4' => ['value' => $this->order['order_sn']], // 订单编号
            'phrase1'           => ['value' => $phrase1], // 审核状态
            'date2'             => ['value' => $this->order['update_time']], // 审核时间
            'thing5'            => ['value' => $sbyy], // 未通过原因
            'thing3'            => ['value' => $thing3], // 备注
        ];
        return [
            'touser'            => $open_id,
            'template_id'       => $this->config['auditNotice'],
            'page'              => '/pages/order-detail/order-detail?id=' . $this->order['order_id'],
            'data'              => $data,
            'miniprogram_state' => $this->miniprogram_state,
            'lang'              => 'zh_CN',
        ];
    }

    /**
     * @Desc 传递订单给收银系统
     *
     * @param $id
     *
     * @return mixed
     */
    public function generatePaymentOrderData($id)
    {
        $order = OrderModel::getOrderDetailFromCar($id);
        $data = [
            'order_id'    => $order['order_sn'], // 预约平台订单号
            'yuyue_mid'   => $order['company_id'], // 检车站ID
            'goods_price' => $order['total_amount'], // 订单金额
            // 'goods_price' => 0.01, // 订单金额
            'add_time'    => $order['add_time'], // 订单创建时间
            'car_master'  => $order['user_name'], // 车主姓名
            'car_num'     => $order['license_number'], // 车牌号
            'yuyue_time'  => $order['yuyue_time'], // 预约日期
            'yuyue_code'  => $order['subscribe_code'], // 预约码
            'other'       => $order['remarks'] ?: '', // 备注
            'new_param'   => 2, // 新的预约平台
        ];
        $url = Config::get('setting.add_order_url'); // 生产环境接口
        // $url = Config::get('setting.test_add_order_url'); // 开发环境接口
        return $this->sendOrderDataToPayment($url, $data);
    }

    /**
     * @Desc 传递订单给收银系统
     *
     * @param $id
     *
     * @return mixed
     */
    public function generatePaymentOrderData2()
    {
        $orders = OrderModel::getOrderDetailFromCar2();
        $err_num = 0;
        $result = ['count' => count($orders)];
        foreach ($orders as $order) {
            $data = [
                'order_id'    => $order['order_sn'], // 预约平台订单号
                'yuyue_mid'   => $order['company_id'], // 检车站ID
                'goods_price' => $order['total_amount'], // 订单金额
                // 'goods_price' => 0.01, // 订单金额
                'add_time'    => $order['add_time'], // 订单创建时间
                'car_master'  => $order['user_name'], // 车主姓名
                'car_num'     => $order['license_number'], // 车牌号
                'yuyue_time'  => $order['yuyue_time'], // 预约日期
                'yuyue_code'  => $order['subscribe_code'], // 预约码
                'other'       => $order['remarks'] ?: '', // 备注
                'new_param'   => 2, // 新的预约平台
            ];
            // $url = Config::get('setting.add_order_url'); // 生产环境接口
            // // $url = Config::get('setting.test_add_order_url'); // 开发环境接口
            // $res =  $this->sendOrderDataToPayment('http://payment.eiphp.com/merchants.php?m=Index&c=orderaction&a=order_add_new', $data);
            $res = $this->sendOrderDataToPayment('http://bqsy.sjxytech.com/merchants.php?m=Index&c=orderaction&a=order_add_new', $data);
            $result[] = $res;
            if ($res['code'] == 0) {
                $err_num++;
            }
        }
        $result['err_num'] = $err_num;
        return $result;
    }

    /**
     * @Desc 向收银系统发送订单数据
     *
     * @param string $url  接口地址
     * @param array  $data 要发送的数据
     *
     * @return mixed
     */
    private function sendOrderDataToPayment($url, $data)
    {
        return (new HttpRequest())->post($url, $data)->json(true);
    }

    /**
     * @Desc 增加接口调用次数
     *
     * @param $param
     */
    public function addInterfaceLog($param)
    {
        $param['date'] = date('Y-m-d');
        if (!array_key_exists('num', $param)) {
            $param['num'] = 1;
        }
        if (!InterfaceLog::getDetail($param)) {
            InterfaceLog::insertData($param);
        } else {
            InterfaceLog::addNum($param);
        }
    }
}